//
//  EmoticonViewController.swift
//  微博分支表情键盘
//
//  Created by JJ on 15/9/11.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit
private let EmoticonCellID="EmoticonCellID"

class EmoticonViewController: UIViewController {
    
    var selectedEmoticonCallBack:(emoticon:Emoticon)->()
    
    init(selecteEmoticon:(emoticon:Emoticon)->()){
        
      self.selectedEmoticonCallBack=selecteEmoticon
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor=UIColor.whiteColor()
       
        setUI()
        
        
    }

   @objc private func clickItem(item:UIBarButtonItem){
    
        let indexPath=NSIndexPath(forRow: 0, inSection: item.tag)
    
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    
    /**
    MARK: -设置UI
    */
    private func setUI(){
        
        view.addSubview(toolBar)
        view.addSubview(collectionView)
        
        let viewDic=["tb":toolBar,"cv":collectionView]
        toolBar.translatesAutoresizingMaskIntoConstraints=false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: viewDic))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[tb]-0-|", options:[], metrics: nil, views: viewDic))
        
        collectionView.translatesAutoresizingMaskIntoConstraints=false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: [], metrics: nil, views: viewDic))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-[tb(44)]-0-|", options: [], metrics: nil, views: viewDic))
        
       prepareToolBar()
       prepareCollectionView()
        
    }
    private func prepareToolBar(){
        
        var items=[UIBarButtonItem]()
        
        var index=0
        toolBar.tintColor=UIColor.darkGrayColor()
        for s in viewModel.packages{
            
            items.append(UIBarButtonItem(title: s.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:"))
            items.last?.tag = index++
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        }
        items.removeLast()
        toolBar.items=items
    }
    
    private func prepareCollectionView(){
        
        collectionView.backgroundColor=UIColor.whiteColor()
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: EmoticonCellID)
        collectionView.dataSource=self
        collectionView.delegate=self
    }
    
    private lazy var toolBar=UIToolbar()
    
    private lazy var collectionView:UICollectionView=UICollectionView(frame:CGRectZero, collectionViewLayout: EmoticonLayout())
    private lazy var viewModel=EmoticonViewModel.shareViewModel
}

extension EmoticonViewController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return viewModel.packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return  viewModel.packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCellID, forIndexPath: indexPath) as! EmoticonViewCell
        
//        cell.backgroundColor=indexPath.item%2 == 0 ? UIColor.greenColor():UIColor.orangeColor()
        
        cell.emoticon=viewModel.emoticon(indexPath)
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        selectedEmoticonCallBack(emoticon: viewModel.emoticon(indexPath))
        
        viewModel.favourate(indexPath)
    }
}

private class EmoticonLayout:UICollectionViewFlowLayout{
    
    private override func prepareLayout() {
        super.prepareLayout()
        let s=collectionView!.bounds.width/7
        itemSize=CGSize(width: s, height: s)
        minimumInteritemSpacing=0
        minimumLineSpacing=0
        
        let h=(collectionView!.bounds.height-3*s) * 0.499
        
        sectionInset=UIEdgeInsetsMake(h, 0, h, 0)
        
        scrollDirection=UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled=true
        
        collectionView?.showsHorizontalScrollIndicator=false
        
    }
}

private class EmoticonViewCell:UICollectionViewCell{
    
    var emoticon:Emoticon?{
        didSet{
          
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
            emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            
            if emoticon!.isRemove{
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUI(){
        contentView.addSubview(emoticonButton)
        emoticonButton.frame=CGRectInset(bounds, 4, 4)
        emoticonButton.backgroundColor=UIColor.whiteColor()
        emoticonButton.titleLabel?.font=UIFont.systemFontOfSize(32)
        emoticonButton.userInteractionEnabled=false
        
    }
    private lazy var emoticonButton:UIButton=UIButton()
}














